<?php

namespace App\Http\Controllers\RBAC;

use App\RBAC\ResType;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class ResTypeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $request->session()->put('status', 'current_user:'.Auth::user());
        return view('rbac/restype');
    }

    public function apiIndex(Request $request)
    {
        return ResType::orderBy('id',"ASC")->paginate(intval($request->per_page));
    }

    public function apiDelete(Request $request,ResType $restype)
    {
        if($restype->delete()){
            return ['msg'=>'ok'];
        }else{
            return ['msg'=>'fail'];
        }
    }

    public function apiStore(Request $request)
    {
        if($request->id){
            $group = ResType::findOrFail(intval($request->id));
            $group->name=$request->name;
            $group->description=$request->description;
            if($group->save()){
                $group = ResType::findOrFail(intval($request->id));
            }
        }else{
            $group = ResType::firstOrCreate(['name' => $request->name,'description'=>$request->description]);
        }
        return $group;
    }
}
